import Vue from 'vue'
import VueRouter from 'vue-router'
import Error from '../components/Error.vue'
import A from '../components/A.vue'
import B from '../components/B.vue'
import Login from '../components/Login.vue'
import Welcome from '../components/Welcome.vue'
import Emp from '../components/Emp.vue'
import Dept from '../components/Dept.vue'


Vue.use(VueRouter)

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'home',
    component: Login
  },
  {
    path: '/login',
    // name: 'about',
    component: Login
  },
  {
    path: '/welcome',
    component: Welcome,
    //一级路由时默认自动跳转指定的二级路由页面
    redirect: '/welcome/emp',
    children: [
      {
        path: 'dept',  //注意这里dept和/dept区别，没有斜杠路径是会带上二级路由中的一级路由,有斜杠是从项目的根目录下访问dept
        name: 'dept',
        component: Dept
      },
      {
        path: 'emp',
        name: 'emp',
        component: Emp
      }
    ]
  },
  {
    path: '/a',
    // name: 'about',
    component: A
  },
  {
    path: '/b',
    component: B
  },
  {
    path: '/error',
    component: Error
  },
  //匹配不到的路径
  {
    path: '*',
    redirect: "/error"
  }
]

const router = new VueRouter({
  routes
})

//路由守卫应该写到const router 后面
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  //去浏览器中获取userid
  const store = window.sessionStorage.getItem('usrId')
  console.log(store)
  if (store == null) {
    return next('/login')
  }
  //继续往后执行
  next();
})

export default router
